package pers.zxk.jlytnews.dao.impl;

import pers.zxk.jlytnews.dao.FoodTypeDao;
import pers.zxk.jlytnews.entity.FoodType;
import pers.zxk.jlytnews.entity.News;
import pers.zxk.jlytnews.util.DBconn;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FoodTypeDaoImpl implements FoodTypeDao {
    @Override
    public boolean addFoodType(String name, String remarks) throws SQLException, ClassNotFoundException {
        boolean flag = false;
        DBconn.init();
        int i = DBconn.addUpdDel("insert into tb_foodtype(name,remarks) " +
                "values('" + name + "','" + remarks + "')");
        if (i > 0) {
            flag = true;
        }
        DBconn.closeConn();
        return flag;
    }

    @Override
    public boolean delFoodType(int id) throws SQLException, ClassNotFoundException {
        boolean flag = false;
        DBconn.init();
        String sql = "delete from tb_foodtype where id=" + id;
        int i = DBconn.addUpdDel(sql);
        if (i > 0) {
            flag = true;
        }
        DBconn.closeConn();
        return flag;
    }

    @Override
    public boolean updateFoodType(int id, String name, String remarks) throws SQLException, ClassNotFoundException {
        boolean flag = false;
        DBconn.init();
        String sql = "update tb_foodtype set name ='" + name
                + "' , remarks ='" + remarks + "' where id = " + id;
        int i = DBconn.addUpdDel(sql);
        if (i > 0) {
            flag = true;
        }
        DBconn.closeConn();
        return flag;
    }

    @Override
    public FoodType getFoodType(int id) throws SQLException, ClassNotFoundException {
        DBconn.init();
        ResultSet rs = DBconn.selectSql("select * from tb_foodtype where id = " + id);
        if (rs.next()) {
            FoodType foodType = new FoodType();
            foodType.setId(rs.getInt("id"));
            foodType.setName(rs.getString("name"));
            foodType.setRemarks(rs.getString("remarks"));
            DBconn.closeConn();
            return foodType;
        } else {
            throw new SQLException("未找到id为"+id+"的数据");
        }
    }

    @Override
    public List<FoodType> getAllFoodType() throws SQLException, ClassNotFoundException {
        List<FoodType> list = new ArrayList<FoodType>();

            DBconn.init();
            ResultSet rs = DBconn.selectSql("select * from tb_foodtype order by id DESC");
            while (rs.next()) {
                FoodType foodType = new FoodType();
                foodType.setId(rs.getInt("id"));
                foodType.setName(rs.getString("name"));
                foodType.setRemarks(rs.getString("remarks"));
                list.add(foodType);
            }
            DBconn.closeConn();
            return list;
    }
}
